<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 会员等级
 *
 * @icon fa fa-circle-o
 */
class UserLev extends Backend
{

    /**
     * UserLev模型对象
     * @var \app\admin\model\deerhome\UserLev
     */
    protected $model = null;
    protected $searchFields = 'name';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\UserLev;
        $this->view->assign("taskTypeList", $this->model->getTaskTypeList());
    }
    /**
     * 设置等级
    */
    public function set_lev(){
        $id=$this->request->param("id",0,'intval');
        $lev=$this->request->param("lev",0,'intval');
        $row = Db::name("deerhome_user_lev")->where('id',$lev)->find();
        if (!$row) {
            $lev=0;
        }
        Db::name("deerhome_user")->where('id',$id)->update([
            'user_lev_id'=>$lev
        ]);
        $this->success("设置成功");
    }
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order('lev asc')
            ->paginate($limit);
        foreach($list->items() as $k=>&$v){
            $v['task']=json_decode($v['task'],true);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        //检查升级条件
        $task=$params['task'];
        $task=(array)json_decode($task,true);
        if(!is_array($task)){
            $this->error('升级条件不能为空');
        }
        if(count($task)==0){
            $this->error('升级条件不能为空');
        }
        //检查$task数组是否name值重复
        $task_name=[];
        foreach($task as $k=>&$v){
            $v['name']=trim($v['name']);
            $v['num']=intval($v['num']);
            if($v['name']==""){
                $this->error('任务类型不能为空，请选择');
            }
            if(in_array($v['name'],$task_name)){
                $this->error('任务类型【'.$v['name'].'】不能重复');
            }
            $task_name[]=$v['name'];
            if($v['num']<=0){
                $this->error('任务类型【'.$v['name'].'】不能为为空或小于等于0');
            }
        }
        //检查升级条件::结束
        $params['lev']=intval($params['lev']);
        if($params['lev']<=0){
            $this->error('等级权重不能为为空或小于等于0');
        }
        $hasLevQz=$this->model->where('lev',$params['lev'])->count();
        if($hasLevQz>0){
            $this->error('等级权重'.$params['lev'].'已经存在，不可重复');
        }

        $params['name']=trim($params['name']);
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $this->model->validateFailException()->validate(
                ['name' => ['unique'=>'deerhome_user_lev,name']],
			    ['name.unique'=> '名称已经存在，请更换']
            );
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
     /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        //检查升级条件
        $task=$params['task'];
        $task=(array)json_decode($task,true);
        if(!is_array($task)){
            $this->error('升级条件不能为空');
        }
        if(count($task)==0){
            $this->error('升级条件不能为空');
        }
        //检查$task数组是否name值重复
        $task_name=[];
        foreach($task as $k=>&$v){
            $v['name']=trim($v['name']);
            $v['num']=intval($v['num']);
            if($v['name']==""){
                $this->error('任务类型不能为空，请选择');
            }
            if(in_array($v['name'],$task_name)){
                $this->error('任务类型【'.$v['name'].'】不能重复');
            }
            $task_name[]=$v['name'];
            if($v['num']<=0){
                $this->error('任务类型【'.$v['name'].'】不能为为空或小于等于0');
            }
        }
        //检查升级条件::结束
        $params['name']=trim($params['name']);
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $row->validateFailException()->validate(
                ['name' => ['unique'=>'deerhome_user_lev,name,'.$row['id']]],
			    ['name.unique'=> '名称已经存在，请更换']
            );
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
    
        $list = $this->model->where($pk, 'in', $ids)->select();
        $has=Db::name("deerhome_user")->where('user_lev_id','in',$ids)->count();
        if($has>0){
            $this->error("该等级下有用户，不能删除");
        }
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
